<?php

namespace apiend\models\searchs;

use common\models\shop\ShopGoods;

/**
 * AssembleProductSearch is the search model class for table "{{%dynamic}}".
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AssembleProductSearch extends ProductSearch {

    /**
     * @var string 聚合标签
     */
    public $tag;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['tag'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function buildQuery() {
        $query = static::find()->alias('t')->active(static::STATUS_ACTIVE);
        $query->innerJoinWith('stats s', true);
        if ($this->tag == 'hot') {
            $query->andWhere([
                'or',
                ['>', 's.hot_time', 0],
                ['>', 's.weights', 0]
            ])->orderBy([
                's.hot_time' => SORT_DESC,
                's.updated_at' => SORT_DESC,
            ]);
        } elseif ($this->tag == 'new') {
            $query->andWhere(['>', 's.on_time', time() - static::NEW_PRODUCT_SHOW_PERIOD * 86400 * 4])
            ->orderBy(['s.on_time' => SORT_DESC]);
        } elseif ($this->tag == 'recommend') {
            $query->andWhere(['>', 's.recommend_time', 0])
            ->orderBy(['s.recommend_time' => SORT_DESC]);
        } elseif ($this->tag == 'discount') {
            $query->innerJoinWith([
                'goods g' => function ($query) {
                    $query->active(ShopGoods::STATUS_ACTIVE)->andWhere(['>', 'g.discount', 0]);
                }
            ]);
        } elseif ($this->tag == 'freeship') {
            $query->innerJoinWith('shipTemplate ship', false)->andWhere(['ship.free' => 1]);
        } else {
            $query->andWhere(['t.id' => 0]);
        }
        return $query;
    }

}
